1
Introdução ao PyTorch: Por que os Tensores Importam
EvoClass-AI002Lecture 1
00:00

Introdução ao PyTorch: Por que os Tensores Importam

O PyTorch é um framework aberto e dinâmico altamente flexível, amplamente utilizado em pesquisas de aprendizado profundo e prototipagem rápida. Em seu cerne, o Tensor é a estrutura de dados indispensável. É uma matriz multidimensional projetada para lidar eficientemente com operações numéricas necessárias para modelos de aprendizado profundo, suportando aceleração por aceleração por GPU automaticamente.

1. Compreendendo a Estrutura de Tensore

Toda entrada, saída e parâmetro do modelo no PyTorch é encapsulado em um Tensor. Eles têm o mesmo propósito que os arrays do NumPy, mas são otimizados para processamento em hardware especializado como GPUs, tornando-os muito mais eficientes para as operações de álgebra linear em larga escala exigidas por redes neurais.

Propriedades-chave definem o tensor:

  • Forma: Define as dimensões dos dados, expressas como uma tupla (por exemplo, $4 \times 32 \times 32$ para um lote de imagens).
  • Tipo: Especifica o tipo numérico dos elementos armazenados (por exemplo, torch.float32 para pesos do modelo, torch.int64 para indexação).
  • Dispositivo: Indica a localização física do hardware: tipicamente 'cpu' ou 'cuda' (GPU da NVIDIA).
Gráfico Dinâmico e Autograd
O PyTorch utiliza um modelo de execução imperativo, o que significa que o gráfico computacional é construído conforme as operações são executadas. Isso permite que o motor embutido de diferenciação automática, Autograd, rastreie cada operação em um Tensor, desde que a propriedade requires_grad=True esteja definida, permitindo o cálculo fácil de gradientes durante a retropropagação.
fundamentals.py
TERMINALbash — pytorch-env
> Ready. Click "Run" to execute.
>
TENSOR INSPECTOR Live

Run code to inspect active tensors
Question 1
Which command creates a $5 \times 5$ tensor containing random numbers following a uniform distribution between 0 and 1?
torch.rand(5, 5)
torch.random(5, 5)
torch.uniform(5, 5)
torch.randn(5, 5)
Question 2
If tensor $A$ is on the CPU, and tensor $B$ is on the CUDA device, what happens if you try to compute $A + B$?
An error occurs because operations require tensors on the same device.
PyTorch automatically moves $A$ to the CUDA device and proceeds.
The operation is performed on the CPU, and the result is returned to the CPU.
Question 3
What is the most common data type (dtype) used for model weights and intermediate calculations in Deep Learning?
torch.float32 (single-precision floating point)
torch.int64 (long integer)
torch.bool
torch.float64 (double-precision floating point)
Challenge: Tensor Manipulation and Shape
Prepare a tensor for a specific matrix operation.
You have a feature vector $F$ of shape $(10,)$. You need to multiply it by a weight matrix $W$ of shape $(10, 5)$. For matrix multiplication (MatMul) to work, $F$ must be 2-dimensional.
Step 1
What should the shape of $F$ be before multiplication with $W$?
Solution:
The inner dimensions must match, so $F$ must be $(1, 10)$. Then $(1, 10) @ (10, 5) \rightarrow (1, 5)$.
Code: F_new = F.unsqueeze(0) or F_new = F.view(1, -1)
Step 2
Perform the matrix multiplication between $F_{new}$ and $W$ (shape $(10, 5)$).
Solution:
The operation is straightforward MatMul.
Code: output = F_new @ W or output = torch.matmul(F_new, W)
Step 3
Which method explicitly returns a tensor with the specified dimensions, allowing you to flatten the tensor back to $(50,)$? (Assume $F$ was $(5, 10)$ initially and is now flattened.)
Solution:
Use the view or reshape methods. The fastest way to flatten is often using -1 for one dimension.
Code: F_flat = F.view(-1) or F_flat = F.reshape(50)